#include <stdlib.h>
#include "thread_pool.h"

pool_task_t* createJobNode(void (*function)(void *), void *argument) {
    pool_task_t *p = malloc(sizeof(pool_task_t));
    p->function = function;
    p->argument = argument;
    p->next = NULL;
    return p;
}

void insertJob(void (*function)(void *), void *argument, pool_task_t **queue, int *task_queue_size) {
    pool_task_t *new_node = createJobNode(function, argument);

    if (*queue == NULL)
        *queue = new_node;
    else {
        pool_task_t* p;
        for (p = *queue; p->next != NULL; p = p->next); // find the last element in the list
        p->next = new_node;
    }

    (*task_queue_size)++;

    return;
}

int removeJob(pool_task_t **queue, int *task_queue_size, void (**function)(void *), void **argument) { // delete all request with that
    if (*queue != NULL) {
        *function = (*queue)->function;
        *argument = (*queue)->argument;

        pool_task_t *temp = *queue;
        *queue = (*queue)->next;
        free(temp);

        (*task_queue_size)--;

        return 0;
    }

    return -999; // the queue is empty
}

void emptyJobQueue(pool_task_t **queue) {
    pool_task_t *p = *queue;

    while(p != NULL) {
        pool_task_t *temp = p;
        p = p->next;
        free(temp);
    }

    *queue = NULL;

    return;
}
